package cn.yshujia.utils;

import cn.yshujia.domain.LoginUser;
import cn.yshujia.domain.vo.UserVO;
import cn.yshujia.repository.UserRepository;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @author YShuJia
 * @create 2024/4/23
 * @description
 */

@Data
@Component
public class SecurityUtils {
	
	private static UserRepository repository;
	
	@Autowired
	public SecurityUtils(UserRepository repository) {
		SecurityUtils.repository = repository;
	}
	
	public static LoginUser getLoginUser() {
		try {
			return (LoginUser) getAuthentication().getPrincipal();
		} catch (Exception e) {
			return null;
		}
	}
	
	public static String getToken(Long id) {
		return repository.getToken(id);
	}
	
	public static void setToken(Long id, String token) {
		repository.setToken(token, id);
	}
	
	public static void setUserVO(UserVO userVO) {
		if (null != userVO) {
			repository.setUser(userVO);
		}
	}
	
	public static LoginUser getLoginUser(String jwt) {
		if (ObjectUtils.isEmpty(jwt) || JwtTokenUtils.isExpired(jwt)) {
			return null;
		}
		Long id = JwtTokenUtils.getUserId(jwt);
		// 获取用户信息
		UserVO user = repository.getUser(id);
		user.setToken(JwtTokenUtils.genAccessToken(id));
		return new LoginUser(user);
	}
	
	public static Authentication getAuthentication() {
		try {
			return SecurityContextHolder.getContext().getAuthentication();
		} catch (Exception e) {
			return null;
		}
	}
	
	public static void setAuthentication(Authentication authentication) {
		SecurityContextHolder.getContext().setAuthentication(authentication);
	}
}